package com.bwie.goods.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.PurchaseRecord;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.PurchaseRecordRequest;
import com.bwie.common.result.PageResult;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.goods.mapper.PurchaseRecordMapper;
import com.bwie.goods.service.PurchaseRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class PurchaseRecordServiceimpl implements PurchaseRecordService {
    @Autowired
    PurchaseRecordMapper purchaseRecordMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public Result<PageResult<PurchaseRecord>> list(PurchaseRecordRequest purchaseRecordRequest) {
        PageHelper.startPage(purchaseRecordRequest.getPageNum(),purchaseRecordRequest.getPageSize());

        Integer roleId = info().getRoleId();
        Integer userId = info().getId();

        List<PurchaseRecord> list = purchaseRecordMapper.list(purchaseRecordRequest,roleId,userId);

        PageInfo<PurchaseRecord> purchaseRecordPageInfo = new PageInfo<>(list);

        return PageResult.toResult(purchaseRecordPageInfo.getTotal(),list);
    }

    @Override
    public Result findById(Integer id) {
        PurchaseRecord purchaseRecord = purchaseRecordMapper.findById(id);
        return Result.success(purchaseRecord,"成功");
    }

    public User info() {
        String header = request.getHeader(TokenConstants.TOKEN);

        String userKey = JwtUtils.getUserKey(header);

        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);

        User user = JSONObject.parseObject(s, User.class);

        return user;
    }

}
